package cn.mrcode.fd.utils.io;

import cn.mrcode.fd.utils.image.ImgCompress;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

/**
 * 文件上传工具类
 * @author : zhuqiang
 * @version : V1.0
 * @date : 2016/1/16 21:02
 */
public class FileUploadUtil {
    public static void springUp(DefaultMultipartHttpServletRequest request) {

    }

    /**
     * springmvc 图片上传，单张图片处理
     * @param request
     * @param rootPath   物理磁盘图片目录路径
     * @param fileName   图片名称
     * @param isCompress 是否原图原尺寸压缩
     * @return true:上传成功
     */
    public static boolean springUpImg(HttpServletRequest request, String rootPath, String fileName, boolean isCompress) {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            //再将request中的数据转化成multipart类型的数据
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator iter = multiRequest.getFileNames();
            try {
                while (iter.hasNext()) {
                    MultipartFile file = multiRequest.getFile((String) iter.next());
                    if (file != null) {
                        File userFolder = new File(rootPath);
                        if (!userFolder.exists()) {
                            userFolder.mkdirs();
                        }
                        File localFile = new File(rootPath, fileName);
                        file.transferTo(localFile);
                        if (isCompress) {
                            ImgCompress.compress(rootPath + fileName);
                        }
                        return true;
                    }
                }
            } catch (IOException e) {
                return false;
            }
        }
        return false;
    }
}
